package com.baihui.crm.export;

import com.baihui.crm.BaihuiResponse;
import com.baihui.crm.BaihuiSession;
import com.baihui.crm.util.BaihuiOptUtil;
import com.baihui.taobao.authorize.TaoBaoSessionInfo;
import com.baihui.taobao.db.*;
import com.baihui.taobao.transition.IViewProgressSupport;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Kevin. User: HSZM1106-0312 Date: 12-1-29 Time: 上午8:45
 */
public class ExportContacts extends ExportData implements IViewProgressSupport {
	public ExportContacts(BaihuiSession baihuiSession,
			TaoBaoSessionInfo taoBaoSessionInfo) {
		super(baihuiSession, taoBaoSessionInfo);
	}

	@Override
	public GeneDAO getDomainDAO() {
		return new UserDAO();
	}

	/**
	 * 导出成交的用户.
	 */
	public List<Map> exportDealCustomer(Long userid) throws Exception {
		List<Map> allData = exportData(Contacts, userid);
		markImportProgress(80);
		return allData;
	}

	@Override
	protected List<Map> constructureData(List<Map> allData, String type,
			Long userid) throws Exception {
		if (allData != null && allData.size() > 0) {
			TradeDAO tradeDAO = new TradeDAO();
			MemberDAO memberDAO = new MemberDAO();
			String tradeSql = "SELECT * from tbtrade where userId= ?  GROUP BY buyerNick ";
			List<Map> tradeList = tradeDAO.findAllObject(tradeSql,
					new Object[] { userid });
			Map tempTradeMap = new HashMap();
			for (Map temp : tradeList) {
				tempTradeMap.put(temp.get("buyerNick"), temp);
			}

			String memberSql = "select * from tbcrmmember where userId= ? ";
			List<Map> members = memberDAO.findAllObject(memberSql,
					new Object[] { userid });
			Map tempMemberMap = new HashMap();
			for (Map mem : members) {
				tempMemberMap.put(mem.get("buyerNick"), mem);
			}
			Map oneTrade = new HashMap<String, Object>();
			for (Map map : allData) {
				if (map.get("nick") != null) {
					String nick = (String) map.get("nick");
					if (tempTradeMap.get(nick) != null) {
						map.put("shipping", tempTradeMap.get(nick));
					} else {
						map.put("shipping", oneTrade);
					}

					if (tempMemberMap.get(nick) != null) {
						map.put("memberInfo", tempMemberMap.get(nick));
					} else {
						map.put("memberInfo", oneTrade);
					}

				}
			}
		}
		return allData;
	}

	@Override
	protected void afterConstructureXMLString(StringBuilder xmlDataStr,
			Map source, Set set, long userid) throws Exception {
		super.afterConstructureXMLString(xmlDataStr, source, set, userid);
		// 计算相关属性
		Map updateData = calcProperty(source, userid);
		if (updateData != null && updateData.size() > 0) {
			java.util.Iterator iter = updateData.keySet().iterator();
			while (iter.hasNext()) {
				String key = (String) iter.next();
				xmlDataStr.append("<FL val=\"" + key + "\">"
						+ updateData.get(key) + "</FL>");
			}
		}
	}

	public Map calcProperty(Map map, long userid) throws Exception {
		TradeDAO tradeDAO = new TradeDAO();
		String nick = (String) map.get("nick");
		Map updateData = new HashMap();
		String sql = "select max(created) as lastTime from tbtrade where userId= ? and buyerNick = ? ";
		Map tmp = tradeDAO.findDate(sql, new Object[] { userid, nick });
		Timestamp lastTime = (Timestamp) tmp.get("lastTime");
		if (lastTime != null) {
			long now = System.currentTimeMillis();
			double ret = (now - lastTime.getTime()) / (24l * 60l * 60l * 1000l);
			int totalDay = new Double(ret).intValue();
			if (ret > (totalDay + 0.5))
				totalDay = totalDay + 1;
			updateData.put("休眠时间", totalDay);
			if (totalDay > 90) {
				updateData.put("用户状态", "休眠");
			} else {
				updateData.put("用户状态", "活跃");
			}
			// 最后一次成交时间
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			updateData.put("最后一笔成交时间", dateFormat.format(lastTime));
		}
		// 保存到exportrecord中
		// saveOrUpdateExportRecord(userid, lastTime, Contacts,
		// map.get("userId"));
		// 计算成交订单数
//		sql = "select count(tbo.oid) as totalNum,sum(tbo.payment) as payment from tborder tbo where tbo.status = ? and tbo.userId= ? and tbo.buyerNick = ? and (exported IS NULL OR exported >= ?) ";
		sql = "select count(tbo.tid) as totalNum,sum(tbo.payment) as payment from tbtrade tbo where tbo.status = ? and tbo.userId= ? and tbo.buyerNick = ? and exported >= ? ";
		tmp = tradeDAO.findDate(sql, new Object[] { "TRADE_FINISHED",userid, nick,0 });
		Long totalCount = 0L;
		if(tmp.get("totalNum") != null){
			totalCount = (Long) tmp.get("totalNum");
		}
		updateData.put("成交订单数", totalCount);
		// 累计消费金额
		// sql = "select sum(totalFee) as totalFee from tbtrade where userId=" +
		// userid + " and  buyerNick = '" + nick + "' ";
		// tmp = tradeDAO.findObject(sql);
		double totalFee = 0.0;
		if(tmp.get("payment") != null){
			totalFee = (Double) tmp.get("payment");
		}
		updateData.put("累计消费金额", totalFee);
		return updateData;
	}

	public void updateCalProperty(long userid) throws Exception {

		String sqlupdate = "select nick,userId,baihuiid from tbuser where exported = 2 and sellerid = "
				+ userid;
		UserDAO userDAO = new UserDAO();
		List<Map> updateDataList = userDAO.findAllObject(sqlupdate);
		// allData中存放的已经是最后一次更改时间不相等的记录了
		TradeDAO tradeDAO = new TradeDAO();
		if (updateDataList != null && updateDataList.size() > 0) {
			for (Map map : updateDataList) {
				String nick = (String) map.get("nick");
				String baihuiid = (String) map.get("baihuiid");
				if (baihuiid == null || baihuiid.length() <= 0)
					continue;
				Map updateData = new HashMap();
				String sql = "select max(created) as lastTime from tbtrade where userId= ? and buyerNick = ? ";
				Map tmp = tradeDAO.findDate(sql, new Object[] { userid, nick });
				Timestamp lastTime = (Timestamp) tmp.get("lastTime");
				if (lastTime != null) {
					long now = System.currentTimeMillis();
					double ret = (now - lastTime.getTime())
							/ (24l * 60l * 60l * 1000l);
					int totalDay = new Double(ret).intValue();
					if (ret > (totalDay + 0.5))
						totalDay = totalDay + 1;
					updateData.put("休眠时间", totalDay);
					if (totalDay > 90) {
						updateData.put("用户状态", "休眠");
					} else {
						updateData.put("用户状态", "活跃");
					}
					// 最后一次成交时间
					SimpleDateFormat dateFormat = new SimpleDateFormat(
							"yyyy-MM-dd hh:mm:ss");
					updateData.put("最后一笔成交时间", dateFormat.format(lastTime));
				}
		
				// 计算成交订单数
				sql = "select count(tbo.tid) as totalNum,sum(tbo.payment) as payment from tbtrade tbo where tbo.status = ? and tbo.userId= ? and tbo.buyerNick = ? and exported >= ? ";
				tmp = tradeDAO.findDate(sql, new Object[] { "TRADE_FINISHED",userid, nick,0 });
				Long totalCount = 0L;
				if(tmp.get("totalNum") != null){
					totalCount = (Long) tmp.get("totalNum");
				}
				updateData.put("成交订单数", totalCount);
				
				// 累计消费金额
				double totalFee = 0.0;
				if(tmp.get("payment") != null){
					totalFee = (Double) tmp.get("payment");
				}
				updateData.put("累计消费金额", totalFee);

				StringBuilder xmlDataString = new StringBuilder();
				xmlDataString.append("<Contacts>");
				xmlDataString.append("<row no=\"1\">");
				java.util.Iterator iter = updateData.keySet().iterator();
				while (iter.hasNext()) {
					String key = (String) iter.next();
					xmlDataString.append("<FL val=\"" + key + "\">"
							+ updateData.get(key) + "</FL>");
				}
				xmlDataString.append("</row>");
				xmlDataString.append("</Contacts>");
				// System.out.println("计算相关属性:" + xmlDataString);
				BaihuiOptUtil.updateRecord(baihuiSession, Contacts,
						xmlDataString.toString(), baihuiid);
				// BaihuiOptUtil.deleteRecord(baihuiSession, Leads, baihuiid);
				String updateString = "update tbuser set exported = 1 where userId = ? and sellerid = ? ";
				userDAO.updateAndInsert(updateString, new Object[] {map.get("userId"),userid});
			}
		}
	}

	/**
	 * 是否已经计算过
	 * 
	 * @param exportRecord
	 * @param userId
	 * @param lastTime
	 * @return
	 */
	private boolean isCalculate(List<Map> exportRecord, Long userId,
			Timestamp lastTime) {
		if (exportRecord == null || exportRecord.size() <= 0
				|| lastTime == null)
			return false;
		for (Map map : exportRecord) {
			// dealUserId,lastDealTime
			Long key = (Long) map.get("dealUserId");
			boolean equalUser = key != null && key.equals(userId);
			if (equalUser) {
				Timestamp dealTime = (Timestamp) map.get("lastDealTime");
				if (dealTime != null
						&& dealTime.getTime() == lastTime.getTime()) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 记录用户的最后一次成交时间
	 * 
	 * @param userid
	 * @param lastTime
	 * @param contacts
	 * @param dealUserId
	 * @throws Exception
	 */
	// private void saveOrUpdateExportRecord(long userid, Timestamp lastTime,
	// String contacts, Object dealUserId) throws Exception {
	// CommonDAO commonDAO = new CommonDAO();
	// boolean exist =
	// commonDAO.isExist("Select * from exportrecord where module='" + Contacts
	// + "' and userid=" + userid + " and dealUserId=" + dealUserId + " ");
	// if (exist) {
	// String sql = "update exportrecord set lastDealTime=? where module='" +
	// Contacts + "' and userid=" + userid + " and dealUserId=" + dealUserId;
	// commonDAO.updateAndInsert(sql, new Object[]{lastTime});
	// } else {
	// String sql =
	// "insert into exportrecord(userid,module,lastDealTime,dealUserId) values(?,?,?,?)";
	// commonDAO.updateAndInsert(sql, new Object[]{userid, Contacts, lastTime,
	// dealUserId});
	// }
	// }

	public void markImportProgress(int progress) {
		// System.out.println("当前进度：" + progress + "%");
		taobaosession.setOrderImportProgress(progress);
	}

	public int viewImportProgress() {
		return taobaosession.getOrderImportProgress();
	}

	@Override
	protected void afterExported(String type, Long userid)
			throws Exception {
		updateCalProperty(userid);
	}
}
